package com.tedu.service;

import com.tedu.vo.ImageVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
 * Author：毕龙
 * Date: 2022/9/22 15:06
 */
@Service
public class FileServiceImpl implements FileService{

    //定义根路径 windows下的路径
    private String preFilePath = "D:/yanan20220913/jt/src/main/resources/image";
    private String preUrlPath = "http://localhost:8091";

    /**
     * 业务逻辑
     * 1.校验图片的类型 jpg|png|gif
     * 2.校验是否为恶意的程序 木马 .exe.jpg
     * 3.将图片进行分目录存储
     * 4.防止图片重名 使用UUID
     *
     * @param file
     * @return
     */
    @Override
    public ImageVo upload(MultipartFile file) {
        //将图片的名字获取
        String fileName = file.getOriginalFilename().toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            //如果图片不满足 则终止程序
            return null;
        }

        try{
            BufferedImage read = ImageIO.read(file.getInputStream());
            int height = read.getHeight();
            int width = read.getWidth();
            if(height == 0 || width==0){
                return null;
            }


            String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String fileDir = preFilePath+datePath;

            //创建目录
            File dirFile = new File(fileDir);
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }

            //防止文件重名  a.png  b.jpg  c.gif
            String uuid = UUID.randomUUID().toString().replace("-", "");
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            fileName = uuid + fileType;

            //文件上传
            String filePath = fileDir + fileName;
            file.transferTo(new File(filePath));

            //封装ImageVO
            String virtualPath = datePath + fileName;

            //封装网络的地址
            String urlPath = filePath;
            System.out.println(urlPath);

            return new ImageVo(virtualPath,urlPath,fileName);

        }catch (Exception e){
            return null;
        }


    }
}
